package org.rcgwt.client.ui.validator.impl;

import java.util.Map;

import org.rcgwt.client.ui.validator.IChecker;
import org.rcgwt.client.ui.validator.IClientValidatorContext;
import org.rcgwt.client.ui.validator.messages.Severity;
import org.rcgwt.client.util.Pattern;

/**
 * Checker which checks year structure with parameters (begin year, end year)
 * 
 * @author Elian ORIOU
 * 
 */

public class YearChecker implements IChecker {
	private static final Pattern YEAR_PATTERN = Pattern.compile("^[0-9]{4}$");

	public Map<String, String> parameters;

	public YearChecker(Map<String, String> parameters) {
		this.parameters = parameters;
	}

	@Override
	public boolean check(IClientValidatorContext context, String s) {
		/* If the year is composed by 4 digits */
		if (YEAR_PATTERN.matches(s)) {
			Integer year = Integer.parseInt(s);
			/* If the two arguments begin-date and end-date are shown */
			if (parameters != null && parameters.containsKey("year.begin")
					&& parameters.containsKey("year.end")) {
				int beginDate = Integer.parseInt(parameters.get("year.begin"));
				int endDate = Integer.parseInt(parameters.get("year.end"));

				if (year >= beginDate && year <= endDate) {
					return true;
				} else {
					context.addMessage(context.getMessagesProvider()
							.BetweenDateErrorShort(beginDate, endDate), context
							.getMessagesProvider().BetweenDateError(beginDate,
									endDate), Severity.WARN);
					return false;
				}
			}
			/* If only begin-date is shown */
			else if (parameters != null && parameters.containsKey("year.begin")) {
				int beginDate = Integer.parseInt(parameters.get("year.begin"));

				if (year >= beginDate) {
					return true;
				} else {
					context.addMessage(context.getMessagesProvider()
							.AfterYearErrorShort(beginDate), context
							.getMessagesProvider().AfterYearError(beginDate),
							Severity.WARN);
					return false;
				}

			}
			/* If only end-date is shown */
			else if (parameters != null && parameters.containsKey("year.end")) {
				int endDate = Integer.parseInt(parameters.get("year.end"));

				if (year <= endDate) {
					return true;
				} else {
					context.addMessage(context.getMessagesProvider()
							.BeforeYearErrorShort(endDate), context
							.getMessagesProvider().BeforeYearError(endDate),
							Severity.WARN);
					return false;
				}
			}
			return true;
		} else {
			return false;
		}
	}
}
